"""
AI驱动的课程内容解析器 - 使用大模型生成课程结构
"""

import json
import asyncio
from typing import List, Dict, Any, Callable, Optional

from src.models.base import (CourseContent, CourseChapter, CoursePoint, ProcessStep, 
                            KnowledgeGraph, KnowledgeNode, KnowledgeEdge, 
                            LearningPath, LearningPathStep)
from src.services import ai_service
from src.utils.logger import get_logger

logger = get_logger(__name__)


class AICourseParser:
    """使用AI大模型的课程内容解析器."""
    
    STEPS = [
        "file_parsing",         # 文件解析
        "content_analysis",     # 内容分析
        "course_introduction",  # 课程介绍生成
        "course_requirements",  # 课程须知生成
        "chapter_generation",   # 章节生成
        "points_generation",    # 要点生成  
        "knowledge_graph",      # 知识图谱生成
        "learning_paths",       # 学习路径生成
        "result_assembly"       # 结果组装
    ]
    
    def __init__(self):
        self.progress_callback: Optional[Callable] = None
        self.current_step = 0
        self.parsed_content = ""
        self.course_title = ""
        self.course_introduction = ""
        self.course_requirements = ""
        self.chapters = []
        self.knowledge_graph = None
        self.learning_paths = []
    
    def set_progress_callback(self, callback: Callable):
        """设置进度回调函数."""
        self.progress_callback = callback
    
    def _update_progress(self, step_name: str, status: str, progress: int, message: str, details: Dict[str, Any] = None):
        """更新进度."""
        if self.progress_callback:
            self.progress_callback(step_name, status, progress, message, details)
    
    async def parse_from_file(self, file_path: str, file_type: str) -> CourseContent:
        """从文件解析课程内容."""
        try:
            # 步骤1: 文件解析
            self._update_progress("file_parsing", "processing", 0, f"正在解析{file_type}文件")
            
            from src.utils.file_parser import FileParser
            file_parser = FileParser()
            
            content = await file_parser.parse_file(file_path, file_type)
            if not content:
                raise ValueError("文件解析失败或内容为空")
            
            self._update_progress("file_parsing", "completed", 100, 
                                f"文件解析完成，提取文本长度: {len(content)}字符",
                                {"extracted_length": len(content), "file_type": file_type})
            
            return await self.parse_from_content(content)
            
        except Exception as e:
            self._update_progress("file_parsing", "failed", 0, f"文件解析失败: {str(e)}")
            raise
    
    async def parse_from_content(self, content: str) -> CourseContent:
        """从文本内容解析课程内容."""
        self.parsed_content = content.strip()
        
        try:
            # 步骤2: 内容分析 + AI生成课程标题
            await self._analyze_content()
            
            # 步骤3: AI生成课程介绍
            await self._generate_course_introduction()
            
            # 步骤4: AI生成课程须知
            await self._generate_course_requirements()
            
            # 步骤5: AI生成章节结构
            await self._generate_chapters()
            
            # 步骤6: AI生成各章节要点
            await self._generate_all_points()
            
            # 步骤7: AI生成知识图谱
            await self._generate_knowledge_graph()
            
            # 步骤8: AI生成学习路径
            await self._generate_learning_paths()
            
            # 步骤9: 结果组装
            await self._assemble_result()
            
            return CourseContent(
                title=self.course_title,
                introduction=self.course_introduction,
                requirements=self.course_requirements,
                chapters=self.chapters,
                knowledge_graph=self.knowledge_graph,
                learning_paths=self.learning_paths
            )
            
        except Exception as e:
            self._update_progress("content_analysis", "failed", 0, f"解析过程失败: {str(e)}")
            raise
    
    async def _analyze_content(self):
        """步骤2: 内容分析和标题生成."""
        self._update_progress("content_analysis", "processing", 0, "正在分析课程内容并生成标题")
        
        try:
            # 使用AI分析内容并生成合适的课程标题
            analysis_prompt = self._get_content_analysis_prompt()
            
            messages = [
                {"role": "user", "content": f"{analysis_prompt}\n\n课程内容:\n{self.parsed_content}"}
            ]
            
            response = await ai_service.generate(messages)
            analysis_result = self._parse_analysis_response(response.content)
            
            self.course_title = analysis_result.get("title", "课程内容")
            
            content_stats = {
                "course_title": self.course_title,
                "content_length": len(self.parsed_content),
                "estimated_chapters": analysis_result.get("estimated_chapters", 1),
                "complexity": analysis_result.get("complexity", "medium")
            }
            
            self._update_progress("content_analysis", "completed", 100, 
                                "内容分析完成，已生成课程标题", content_stats)
            
        except Exception as e:
            logger.error(f"内容分析失败: {e}")
            # 回退到简单分析
            self.course_title = "课程内容"
            self._update_progress("content_analysis", "completed", 100, 
                                "内容分析完成（使用默认标题）", 
                                {"course_title": self.course_title, "content_length": len(self.parsed_content)})
    
    async def _generate_course_introduction(self):
        """步骤3: AI生成课程介绍."""
        self._update_progress("course_introduction", "processing", 0, "正在使用AI生成课程介绍")
        
        try:
            intro_prompt = self._get_course_introduction_prompt()
            
            messages = [
                {"role": "user", "content": f"{intro_prompt}\n\n课程标题: {self.course_title}\n\n课程内容:\n{self.parsed_content[:2000]}"}
            ]
            
            response = await ai_service.generate(messages, temperature=0.7)
            self.course_introduction = self._parse_text_response(response.content)
            
            intro_stats = {
                "introduction_length": len(self.course_introduction),
                "course_title": self.course_title
            }
            
            self._update_progress("course_introduction", "completed", 100,
                                "课程介绍生成完成", intro_stats)
            
        except Exception as e:
            logger.error(f"课程介绍生成失败: {e}")
            # 回退到默认介绍
            self.course_introduction = f"欢迎学习{self.course_title}！本课程将带您深入了解相关知识和技能，通过系统化的学习帮助您掌握核心概念和实践应用。"
            self._update_progress("course_introduction", "completed", 100,
                                "课程介绍生成完成（使用默认介绍）",
                                {"introduction_length": len(self.course_introduction)})
    
    async def _generate_course_requirements(self):
        """步骤4: AI生成课程须知."""
        self._update_progress("course_requirements", "processing", 0, "正在使用AI生成课程须知")
        
        try:
            req_prompt = self._get_course_requirements_prompt()
            
            messages = [
                {"role": "user", "content": f"{req_prompt}\n\n课程标题: {self.course_title}\n\n课程内容概述:\n{self.parsed_content[:1500]}"}
            ]
            
            response = await ai_service.generate(messages, temperature=0.6)
            self.course_requirements = self._parse_text_response(response.content)
            
            req_stats = {
                "requirements_length": len(self.course_requirements),
                "course_title": self.course_title
            }
            
            self._update_progress("course_requirements", "completed", 100,
                                "课程须知生成完成", req_stats)
            
        except Exception as e:
            logger.error(f"课程须知生成失败: {e}")
            # 回退到默认须知
            self.course_requirements = "学习本课程建议具备基础的相关知识背景。请确保有足够的学习时间，建议按照章节顺序进行学习，并及时练习和复习所学内容。"
            self._update_progress("course_requirements", "completed", 100,
                                "课程须知生成完成（使用默认须知）",
                                {"requirements_length": len(self.course_requirements)})
    
    async def _generate_chapters(self):
        """步骤5: AI生成章节结构."""
        self._update_progress("chapter_generation", "processing", 0, "正在使用AI生成课程章节")
        
        try:
            chapter_prompt = self._get_chapter_generation_prompt()
            
            messages = [
                {"role": "user", "content": f"{chapter_prompt}\n\n课程标题: {self.course_title}\n\n课程内容:\n{self.parsed_content}"}
            ]
            
            response = await ai_service.generate(messages, temperature=0.7)
            chapters_data = self._parse_chapters_response(response.content)
            
            # 创建章节对象（暂时不含要点）
            self.chapters = []
            for chapter_data in chapters_data:
                chapter = CourseChapter(
                    title=chapter_data["title"],
                    description=chapter_data["description"],
                    points=[]  # 稍后填充
                )
                self.chapters.append(chapter)
            
            chapter_info = {
                "chapter_count": len(self.chapters),
                "chapter_titles": [ch.title for ch in self.chapters]
            }
            
            self._update_progress("chapter_generation", "completed", 100,
                                f"章节生成完成，共生成{len(self.chapters)}个章节", chapter_info)
            
        except Exception as e:
            logger.error(f"章节生成失败: {e}")
            # 回退到单章节
            self.chapters = [CourseChapter(
                title="主要内容",
                description="课程核心内容概述", 
                points=[]
            )]
            self._update_progress("chapter_generation", "completed", 100,
                                "章节生成完成（使用默认章节）", 
                                {"chapter_count": 1, "chapter_titles": ["主要内容"]})
    
    async def _generate_all_points(self):
        """步骤6: AI为所有章节生成要点."""
        self._update_progress("points_generation", "processing", 0, "开始为各章节生成要点")
        
        total_level1_points = 0
        total_level2_points = 0
        
        try:
            for i, chapter in enumerate(self.chapters):
                self._update_progress("points_generation", "processing", 
                                    int((i / len(self.chapters)) * 80),
                                    f"正在为第{i+1}章节生成要点: {chapter.title}")
                
                # 为当前章节生成要点
                chapter_points = await self._generate_chapter_points(chapter, i)
                chapter.points = chapter_points
                
                # 统计要点数量
                level1_count = len(chapter_points)
                level2_count = sum(len(p.sub_points) if p.sub_points else 0 for p in chapter_points)
                
                total_level1_points += level1_count
                total_level2_points += level2_count
                
                progress = int(((i + 1) / len(self.chapters)) * 100)
                self._update_progress("points_generation", "processing", progress,
                                    f"第{i+1}章节要点生成完成: {level1_count}个一级要点，{level2_count}个二级要点")
            
            points_info = {
                "level1_points": total_level1_points,
                "level2_points": total_level2_points
            }
            
            self._update_progress("points_generation", "completed", 100,
                                f"要点生成完成，共{total_level1_points}个一级要点，{total_level2_points}个二级要点",
                                points_info)
            
        except Exception as e:
            logger.error(f"要点生成失败: {e}")
            self._update_progress("points_generation", "completed", 100,
                                "要点生成完成（部分使用默认要点）", 
                                {"level1_points": total_level1_points, "level2_points": total_level2_points})
    
    async def _generate_chapter_points(self, chapter: CourseChapter, chapter_index: int) -> List[CoursePoint]:
        """为单个章节生成要点."""
        try:
            points_prompt = self._get_points_generation_prompt()
            
            # 获取相关内容片段
            content_segment = self._get_chapter_content_segment(chapter.title, chapter_index)
            
            messages = [
                {"role": "user", "content": f"{points_prompt}\n\n章节标题: {chapter.title}\n章节描述: {chapter.description}\n\n相关内容:\n{content_segment}"}
            ]
            
            response = await ai_service.generate(messages, temperature=0.6)
            points_data = self._parse_points_response(response.content)
            
            # 创建要点对象
            points = []
            for point_data in points_data:
                # 创建一级要点
                main_point = CoursePoint(
                    title=point_data["title"],
                    description=point_data["description"],
                    level=1
                )
                
                # 创建二级要点
                if "sub_points" in point_data and point_data["sub_points"]:
                    sub_points = []
                    for sub_data in point_data["sub_points"]:
                        sub_point = CoursePoint(
                            title=sub_data["title"],
                            description=sub_data["description"],
                            level=2
                        )
                        sub_points.append(sub_point)
                    main_point.sub_points = sub_points
                
                points.append(main_point)
            
            return points
            
        except Exception as e:
            logger.warning(f"章节 '{chapter.title}' 要点生成失败: {e}，使用默认要点")
            # 返回默认要点
            return [CoursePoint(
                title=f"{chapter.title}要点",
                description=f"关于{chapter.title}的主要内容",
                level=1
            )]
    
    async def _generate_knowledge_graph(self):
        """步骤7: AI生成知识图谱."""
        self._update_progress("knowledge_graph", "processing", 0, "正在生成课程知识图谱")
        
        try:
            graph_prompt = self._get_knowledge_graph_prompt()
            
            # 构造章节和要点信息
            course_structure = self._get_course_structure_for_graph()
            
            messages = [
                {"role": "user", "content": f"{graph_prompt}\n\n课程结构:\n{course_structure}"}
            ]
            
            response = await ai_service.generate(messages, temperature=0.5)
            graph_data = self._parse_knowledge_graph_response(response.content)
            
            # 创建知识图谱对象
            nodes = []
            for node_data in graph_data.get("nodes", []):
                node = KnowledgeNode(
                    id=node_data["id"],
                    title=node_data["title"],
                    description=node_data["description"],
                    type=node_data["type"],
                    level=node_data["level"],
                    chapter_id=node_data.get("chapter_id")
                )
                nodes.append(node)
            
            edges = []
            for edge_data in graph_data.get("edges", []):
                edge = KnowledgeEdge(
                    from_node=edge_data["from_node"],
                    to_node=edge_data["to_node"],
                    relationship=edge_data["relationship"],
                    weight=edge_data.get("weight", 1.0)
                )
                edges.append(edge)
            
            self.knowledge_graph = KnowledgeGraph(nodes=nodes, edges=edges)
            
            graph_info = {
                "node_count": len(nodes),
                "edge_count": len(edges),
                "node_types": list(set(n.type for n in nodes))
            }
            
            self._update_progress("knowledge_graph", "completed", 100, 
                                f"知识图谱生成完成，包含{len(nodes)}个知识点和{len(edges)}个关系", 
                                graph_info)
            
        except Exception as e:
            logger.warning(f"知识图谱生成失败: {e}，跳过该步骤")
            self.knowledge_graph = None
            self._update_progress("knowledge_graph", "completed", 100, 
                                "知识图谱生成跳过", {"error": str(e)})

    async def _generate_learning_paths(self):
        """步骤8: AI生成学习路径."""
        self._update_progress("learning_paths", "processing", 0, "正在生成推荐学习路径")
        
        try:
            paths_prompt = self._get_learning_paths_prompt()
            
            # 构造课程信息和知识图谱信息
            course_info = self._get_course_info_for_paths()
            
            messages = [
                {"role": "user", "content": f"{paths_prompt}\n\n课程信息:\n{course_info}"}
            ]
            
            response = await ai_service.generate(messages, temperature=0.6)
            paths_data = self._parse_learning_paths_response(response.content)
            
            # 创建学习路径对象
            paths = []
            for path_data in paths_data:
                steps = []
                for step_data in path_data["steps"]:
                    step = LearningPathStep(
                        step_id=step_data["step_id"],
                        title=step_data["title"],
                        description=step_data["description"],
                        knowledge_nodes=step_data.get("knowledge_nodes", []),
                        estimated_time=step_data["estimated_time"],
                        difficulty=step_data["difficulty"],
                        prerequisites=step_data.get("prerequisites", [])
                    )
                    steps.append(step)
                
                path = LearningPath(
                    path_name=path_data["path_name"],
                    description=path_data["description"],
                    target_audience=path_data["target_audience"],
                    total_time=path_data["total_time"],
                    steps=steps
                )
                paths.append(path)
            
            self.learning_paths = paths
            
            paths_info = {
                "path_count": len(paths),
                "path_names": [p.path_name for p in paths],
                "total_steps": sum(len(p.steps) for p in paths)
            }
            
            self._update_progress("learning_paths", "completed", 100,
                                f"学习路径生成完成，共{len(paths)}条路径", paths_info)
            
        except Exception as e:
            logger.warning(f"学习路径生成失败: {e}，跳过该步骤") 
            self.learning_paths = []
            self._update_progress("learning_paths", "completed", 100,
                                "学习路径生成跳过", {"error": str(e)})

    async def _assemble_result(self):
        """步骤9: 结果组装."""
        self._update_progress("result_assembly", "processing", 0, "正在组装最终结果")
        
        # 验证数据完整性
        if not self.course_title:
            self.course_title = "课程内容"
        
        if not self.chapters:
            self.chapters = [CourseChapter(
                title="主要内容",
                description="课程核心内容",
                points=[]
            )]
        
        result_info = {
            "chapters": len(self.chapters),
            "knowledge_nodes": len(self.knowledge_graph.nodes) if self.knowledge_graph else 0,
            "learning_paths": len(self.learning_paths)
        }
        
        self._update_progress("result_assembly", "completed", 100, "课程内容解析完成", result_info)
    
    def _get_content_analysis_prompt(self) -> str:
        """获取内容分析的提示词."""
        return """请分析以下课程内容，并返回JSON格式的分析结果：

任务要求：
1. 为课程生成一个合适的标题（简洁、准确）
2. 估算合理的章节数量（1-8个）
3. 评估内容复杂度（simple/medium/complex）

返回格式（纯JSON，不要markdown代码块）：
{
    "title": "课程标题",
    "estimated_chapters": 3,
    "complexity": "medium"
}"""
    
    def _get_course_introduction_prompt(self) -> str:
        """获取课程介绍生成的提示词."""
        return """请为这个课程生成一份吸引人的介绍文本：

任务要求：
1. 介绍文本应该有200-300字，富有吸引力和专业性
2. 明确说明课程的价值和学习收益
3. 突出课程的特色和亮点
4. 使用鼓励性的语言激发学习兴趣
5. 语言流畅、逻辑清晰

请直接返回介绍文本，不要使用markdown格式或代码块。"""
    
    def _get_course_requirements_prompt(self) -> str:
        """获取课程须知生成的提示词."""
        return """请为这个课程生成详细的学习须知：

任务要求：
1. 生成150-250字的课程须知
2. 包含学习前提条件和基础要求
3. 说明学习方法和建议时间安排
4. 提及需要的学习工具或环境（如适用）
5. 给出学习效果的预期和建议
6. 语言简洁明了，条理清晰

请直接返回须知文本，不要使用markdown格式或代码块。"""
    
    def _get_chapter_generation_prompt(self) -> str:
        """获取章节生成的提示词."""
        return """请根据课程内容生成章节结构，返回JSON格式：

任务要求：
1. 生成2-6个有意义的章节
2. 每个章节要有清晰的标题和详细描述（100-200字）
3. 章节描述要详细说明该章节的学习目标、主要内容和重点知识
4. 章节应该逻辑清晰、循序渐进

返回格式（纯JSON，不要markdown代码块）：
[
    {
        "title": "第一章：基础概念与理论框架",
        "description": "本章将系统介绍课程的基础概念和核心理论框架。学习者将掌握相关领域的基本术语、概念定义以及理论基础。通过本章学习，能够建立完整的知识体系，理解各个概念之间的逻辑关系，为后续章节的深入学习奠定坚实基础。重点内容包括核心概念解析、理论体系构建和基础原理阐述。"
    },
    {
        "title": "第二章：实践应用与案例分析", 
        "description": "本章通过丰富的实际案例和实践应用，帮助学习者将理论知识转化为实际操作能力。详细分析多个典型案例，展示理论在实际工作中的应用方法和技巧。学习者将学会如何识别问题、分析问题并运用所学理论解决实际问题。重点培养实践操作能力和问题解决思维。"
    }
]"""
    
    def _get_points_generation_prompt(self) -> str:
        """获取要点生成的提示词."""
        return """请为这个章节生成学习要点，返回JSON格式：

任务要求：
1. 生成3-5个一级要点，每个要点要有清晰的标题和详细描述（60-100字）
2. 为重要的一级要点生成1-3个二级要点，每个二级要点描述50-80字
3. 要点描述要详细说明学习内容、掌握程度和应用场景
4. 确保要点覆盖章节的核心内容，层次清晰，逻辑完整

返回格式（纯JSON，不要markdown代码块）：
[
    {
        "title": "核心概念理解与应用",
        "description": "深入理解本章节的基本概念和核心定义，掌握相关术语的准确含义和使用场景。能够准确识别和区分不同概念，理解概念间的内在联系和逻辑关系，并能在实际情况中正确运用这些概念进行分析和判断。",
        "sub_points": [
            {
                "title": "基础概念掌握",
                "description": "熟练掌握本章涉及的所有关键术语和基本概念的准确定义，理解其产生背景和发展历程，能够用自己的语言清楚解释每个概念的内涵和外延。"
            },
            {
                "title": "概念关系分析",
                "description": "深入理解各个概念之间的逻辑关系、层次结构和相互影响，能够构建完整的概念体系图，分析概念间的因果关系、包含关系和并列关系。"
            }
        ]
    },
    {
        "title": "实践技能培养与应用",
        "description": "通过理论与实践相结合的方式，培养运用所学知识解决实际问题的能力。掌握相关的操作方法和技巧，能够在不同情境下灵活运用理论知识，具备独立分析问题和制定解决方案的实践能力。"
    }
]"""
    
    def _parse_analysis_response(self, response: str) -> Dict[str, Any]:
        """解析内容分析响应."""
        try:
            # 清理响应内容
            response = response.strip()
            if response.startswith("```json"):
                response = response[7:-3].strip()
            elif response.startswith("```"):
                response = response[3:-3].strip()
            
            return json.loads(response)
        except Exception as e:
            logger.warning(f"解析分析响应失败: {e}")
            return {"title": "课程内容", "estimated_chapters": 1, "complexity": "medium"}
    
    def _parse_text_response(self, response: str) -> str:
        """解析纯文本响应."""
        try:
            # 清理响应内容
            response = response.strip()
            
            # 移除可能的markdown代码块标记
            if response.startswith("```"):
                lines = response.split('\n')
                if len(lines) > 2:
                    # 移除开头和结尾的```行
                    response = '\n'.join(lines[1:-1]).strip()
            
            # 移除引号包围（如果存在）
            if response.startswith('"') and response.endswith('"'):
                response = response[1:-1]
            
            return response
            
        except Exception as e:
            logger.warning(f"解析文本响应失败: {e}")
            return response.strip()
    
    def _parse_chapters_response(self, response: str) -> List[Dict[str, str]]:
        """解析章节生成响应."""
        try:
            response = response.strip()
            if response.startswith("```json"):
                response = response[7:-3].strip()
            elif response.startswith("```"):
                response = response[3:-3].strip()
            
            chapters = json.loads(response)
            if isinstance(chapters, list) and chapters:
                return chapters
            else:
                raise ValueError("Invalid chapters format")
        except Exception as e:
            logger.warning(f"解析章节响应失败: {e}")
            return [{"title": "主要内容", "description": "课程核心内容概述"}]
    
    def _parse_points_response(self, response: str) -> List[Dict[str, Any]]:
        """解析要点生成响应."""
        try:
            response = response.strip()
            if response.startswith("```json"):
                response = response[7:-3].strip()
            elif response.startswith("```"):
                response = response[3:-3].strip()
            
            points = json.loads(response)
            if isinstance(points, list) and points:
                return points
            else:
                raise ValueError("Invalid points format")
        except Exception as e:
            logger.warning(f"解析要点响应失败: {e}")
            return [{"title": "主要要点", "description": "本章节的核心内容"}]
    
    def _get_chapter_content_segment(self, chapter_title: str, chapter_index: int) -> str:
        """获取章节相关的内容片段."""
        # 简单实现：按章节索引分割内容
        lines = self.parsed_content.split('\n')
        
        # 计算每个章节大约的行数
        lines_per_chapter = max(1, len(lines) // len(self.chapters)) if self.chapters else len(lines)
        
        start_line = chapter_index * lines_per_chapter
        end_line = min((chapter_index + 1) * lines_per_chapter, len(lines))
        
        segment = '\n'.join(lines[start_line:end_line]).strip()
        
        # 如果片段太短，返回全部内容
        if len(segment) < 50:
            return self.parsed_content
        
        return segment[:1000]  # 限制长度避免token过多
    
    def _get_knowledge_graph_prompt(self) -> str:
        """获取知识图谱生成的提示词."""
        return """请基于课程结构生成知识图谱，返回JSON格式：

任务要求：
1. 分析课程中的关键知识点，生成知识节点
2. 每个节点包含：id、title、description、type（concept/skill/application）、level（1-3）、chapter_id
3. 分析知识点之间的关系，生成边连接
4. 关系类型：prerequisite（前置要求）、includes（包含）、applies_to（应用于）

返回格式（纯JSON，不要markdown代码块）：
{
    "nodes": [
        {
            "id": "node_1",
            "title": "基础概念",
            "description": "课程的基础理论概念",
            "type": "concept",
            "level": 1,
            "chapter_id": "chapter_1"
        }
    ],
    "edges": [
        {
            "from_node": "node_1",
            "to_node": "node_2", 
            "relationship": "prerequisite",
            "weight": 1.0
        }
    ]
}"""

    def _get_learning_paths_prompt(self) -> str:
        """获取学习路径生成的提示词."""
        return """请基于课程信息生成2-3条不同的学习路径，返回JSON格式：

任务要求：
1. 为不同类型的学习者设计路径：初学者、有基础者、高级学习者
2. 每条路径包含多个学习步骤，步骤要有清晰的顺序和时间估算
3. 每个步骤要指明难度级别和前置要求

返回格式（纯JSON，不要markdown代码块）：
[
    {
        "path_name": "初学者快速入门",
        "description": "适合零基础学习者的渐进式学习路径",
        "target_audience": "初学者",
        "total_time": 480,
        "steps": [
            {
                "step_id": "step_1",
                "title": "基础概念学习",
                "description": "掌握课程的基本概念和术语",
                "knowledge_nodes": ["node_1", "node_2"],
                "estimated_time": 60,
                "difficulty": "easy",
                "prerequisites": []
            }
        ]
    }
]"""

    def _get_course_structure_for_graph(self) -> str:
        """获取用于知识图谱生成的课程结构信息."""
        structure_info = f"课程标题: {self.course_title}\n\n"
        
        for i, chapter in enumerate(self.chapters):
            structure_info += f"章节{i+1}: {chapter.title}\n"
            structure_info += f"描述: {chapter.description}\n"
            
            if chapter.points:
                structure_info += "要点:\n"
                for point in chapter.points:
                    structure_info += f"  - {point.title}: {point.description}\n"
                    if point.sub_points:
                        for sub_point in point.sub_points:
                            structure_info += f"    * {sub_point.title}: {sub_point.description}\n"
            structure_info += "\n"
        
        return structure_info

    def _get_course_info_for_paths(self) -> str:
        """获取用于学习路径生成的课程信息."""
        info = f"课程标题: {self.course_title}\n\n"
        info += f"章节数量: {len(self.chapters)}\n"
        
        for i, chapter in enumerate(self.chapters):
            info += f"章节{i+1}: {chapter.title}\n"
            point_count = len(chapter.points)
            sub_point_count = sum(len(p.sub_points) if p.sub_points else 0 for p in chapter.points)
            info += f"  要点数量: {point_count}个一级要点，{sub_point_count}个二级要点\n"
        
        if self.knowledge_graph:
            info += f"\n知识图谱: {len(self.knowledge_graph.nodes)}个知识点\n"
        
        return info

    def _parse_knowledge_graph_response(self, response: str) -> Dict[str, Any]:
        """解析知识图谱生成响应."""
        try:
            response = response.strip()
            if response.startswith("```json"):
                response = response[7:-3].strip()
            elif response.startswith("```"):
                response = response[3:-3].strip()
            
            graph_data = json.loads(response)
            if "nodes" in graph_data and "edges" in graph_data:
                return graph_data
            else:
                raise ValueError("Invalid knowledge graph format")
        except Exception as e:
            logger.warning(f"解析知识图谱响应失败: {e}")
            return {"nodes": [], "edges": []}

    def _parse_learning_paths_response(self, response: str) -> List[Dict[str, Any]]:
        """解析学习路径生成响应."""
        try:
            response = response.strip()
            if response.startswith("```json"):
                response = response[7:-3].strip()
            elif response.startswith("```"):
                response = response[3:-3].strip()
            
            paths_data = json.loads(response)
            if isinstance(paths_data, list) and paths_data:
                return paths_data
            else:
                raise ValueError("Invalid learning paths format")
        except Exception as e:
            logger.warning(f"解析学习路径响应失败: {e}")
            return []